<?php

namespace app\common\model;

use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 缓存表
 */
class trCache extends Model
{
    protected $pk = 'key';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "cache"; //表名

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        return $data;
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    //保存
    public static function saveCache($data){
        if(!is_array($data) || empty($data["key"]) || empty($data["value"]))
            return false;
        $value = $data["value"];
        $data["value"] = serialize($data["value"]);
        $option = null;
        if(!empty($data["time"])){
            $option = $data["time"];
            $data["time"] = time() + $data["time"];
        }
        $data["mall_id"] = request()->mallData["id"];
        if((C_get("{$data["mall_id"]}_isExist_c_{$data["key"]}")) !== false || self::getCount(["key" => $data["key"], "mall_id" => $data["mall_id"]])){ //更新
            if(self::update($data, ["key" => $data["key"], "mall_id" => $data["mall_id"]])) {
                C_set("{$data["mall_id"]}_".$data["key"], $value, $option);
                C_set("{$data["mall_id"]}_"."isExist_c_{$data["key"]}", true, $option);
                return true;
            }
        }else{
            if(self::create($data)){
                C_set("{$data["mall_id"]}_".$data["key"], $value, $option);
                C_set("{$data["mall_id"]}_"."isExist_c_{$data["key"]}", true, $option);
                return true;
            }
        }
        return false;
    }

    //获取某字段的值
    public static function getValue($field, $filter = [], $del = true){
        if(!is_array($field)){
            $filter["mall_id"] = request()->mallData["id"];
            if($field == "value"){
                if (isset($filter["key"])) {
                    $key = $filter["key"];
                }else{
                    $key = self::getValue("key", $filter);
                }
                if(($data = C_get("{$filter["mall_id"]}_".$key)) === false){
                    $item = self::where($filter)->field($field.",time")->find();
                    if(!empty($item)){
                        if(!empty($item["time"]) && $item["time"] < time()){ // 过期了
                            if($del) {
                                self::del($filter["key"]);
                            }
                        }else {
                            $data = unserialize($item["value"]);
                            C_set("{$filter["mall_id"]}_".$key, $data, !empty($item["time"]) ? ($item["time"] - time()) : null);
                        }
                    }
                }
                return $data;
            }
            return self::where($filter)->value($field);
        }
        return false;
    }

    //根据删除数据
    public static function del($key){
        if (!$key) {
            return false;
        }
        $mall_id = request()->mallData["id"];
        C_set("{$mall_id}_".$key, null);
        C_set("{$mall_id}_"."isExist_c_{$key}", null);

        $result = self::where("key", $key)->where("mall_id", $mall_id)->delete();

        //删除过期的数据
        $key = self::where("time", "<", time())->where("mall_id", $mall_id)->column("key");
        if(!empty($key)){
            $result = self::where("key", "in", $key)->where("mall_id", $mall_id)->delete();
            foreach ($key as $id){
                C_set("{$mall_id}_".$id, null);
                C_set("{$mall_id}_"."isExist_c_{$id}", null);
            }
        }
        return $result;
    }

    //根据删除数据
    public static function delByVague($key){
        if (!$key) {
            return false;
        }
        $mall_id = request()->mallData["id"];
        $result = self::where("key", "like", "{$key}%")->where("mall_id", $mall_id)->delete();
        if($result && ($redisObject = redis_object()) !== false){
            $res = $redisObject->getKeys("{$mall_id}_"."{$key}*");
            foreach ($res as $id){
                C_set($id, null);
            }
            $res = $redisObject->getKeys("{$mall_id}_"."isExist_c_{$key}*");
            foreach ($res as $id){
                C_set($id, null);
            }
        }
        return $result;
    }
}